<?php
date_default_timezone_set('Asia/Shanghai');

/**
 * @copyright (c) 2019 aircheng.com
 * @file aliyun_live.php
 * @brief 阿里云直播插件
 * @date 2019/7/5 10:41:41
 * @version 5.2
 */
class aliyun_live extends pluginBase
{
    private $client = null;
    private $rong = null;
    private $AccessKey;
    private $SecretKey;
    private $AppName;
    private $PushUrlKey;
    private $PlayUrlKey;
    private $PushUrl;
    private $PlayUrl;
    private $RongAppKey;
    private $RongAppSecret;
    private $Examine;
    private $UnPass;
    private $pageSize = 20;
    private $pageObj = null;//分页类库

    public function __construct()
    {
        $AliyunPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'SDK' . DIRECTORY_SEPARATOR . 'aliyun-php-sdk-core' . DIRECTORY_SEPARATOR . 'Config.php';
        $RongPath   = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'SDK' . DIRECTORY_SEPARATOR . 'RongCloud' . DIRECTORY_SEPARATOR . 'RongCloud.php';
        if (is_file($AliyunPath) && is_file($RongPath))
        {
            include($AliyunPath);
            include($RongPath);
            $config                   = $this->config();
            $this->AccessKey          = $config['AccessKey'];
            $this->SecretKey          = $config['SecretKey'];
            $this->AppName            = $config['AppName'];
            $this->PushUrlKey         = $config['PushUrlKey'];
            $this->PlayUrlKey         = $config['PlayUrlKey'];
            $this->PushUrl            = $config['PushUrl'];
            $this->PlayUrl            = $config['PlayUrl'];
            $this->Examine            = $config['Examine'];
            $this->RongAppKey         = $config['RongAppKey'];
            $this->RongAppSecret      = $config['RongAppSecret'];
            $this->Examine            = $config['Examine'];
            $this->UnPass             = $config['UnPass'];
            $this->pageObj            = new IPaging();
            $this->pageObj->firstpage = 1;
            $this->pageObj->pagesize  = $this->pageSize;
            $this->pageObj->totalpage = 0;
            $this->pageObj->index     = IReq::get('page') ? IFilter::act(IReq::get('page'), 'int') : 1;
        } else
        {
            throw new IException("文件丢失");
        }
    }

    //名字
    public static function name()
    {
        return "商家卖货直播插件";
    }

    //描述
    public static function description()
    {
        return "传统电商,都不想错过的电商直播的红利,引流卖货不容错过,自定义选择直播模板,直播采用阿里云SDK,<a href='https://www.aliyun.com/product/live' target='_blank'>免费注册</a> <br/>聊天采用融云IM SDK <a href='https://www.rongcloud.cn/product/im' target='_blank'>免费注册</a>";
    }

    //插件默认配置
    public static function configName()
    {
        $configData = array(
            'AccessKey'     => array("name" => "阿里云AccessKey", "type" => "text", "pattern" => "required"),
            'SecretKey'     => array("name" => "阿里云SecretKey", "type" => "text", "pattern" => "required"),
            'AppName'       => array("name" => "直播应用名称", "type" => "text", "pattern" => "required"),
            'PushUrlKey'    => array("name" => "推流鉴权主KEY", "type" => "text", "pattern" => "required"),
            'PlayUrlKey'    => array("name" => "拉流鉴权主KEY", "type" => "text", "pattern" => "required"),
            'PushUrl'       => array("name" => "推流域名", "type" => "text", "pattern" => "required"),
            'PlayUrl'       => array("name" => "拉流域名", "type" => "text", "pattern" => "required"),
            'RongAppKey'    => array("name" => "融云appKey", "type" => "text", "pattern" => "required"),
            'RongAppSecret' => array("name" => "融云appSecret", "type" => "text", "pattern" => "required"),
            'Examine'       => array("name" => "是否需要审核", "type" => "select", "value" => array("否" => '0',"是" => '1'), "pattern" => "required"),
            'UnPass'        => array("name" => "未直播是否可以进入房间", "type" => "select", "value" => array("是" => '1',"否" => '0'), "pattern" => "required"),
        );
        return $configData;
    }

    //插件安装
    public static function install()
    {
        $liveObj = new IModel('aliyun_live');
        if (!$liveObj->exists())
        {
            $data = array(
                "comment" => '主播记录表',
                "column"  => array(
                    "id"        => array("type" => "int(11) unsigned", 'auto_increment' => 1),
                    "room_name" => array("type" => "varchar(100)", "comment" => "直播名称"),
                    "content"   => array("type" => "text", "comment" => "json数据格式"),
                    "seller_id" => array("type" => "int(11) unsigned", "default" => "0", "comment" => "商家ID"),
                    "status"    => array("type" => "tinyint(1)", "default" => "0", "comment" => "审核状态 0:审核中 1:审核通过")
                ),
                "index"   => array("primary" => "id", "key" => "seller_id"),
            );
            $liveObj->setData($data);
            unset($data);
            $liveObj->createTable();
            //外键约束
            $liveRelSellerDB = new IModel('aliyun_live,seller');
            $liveRelSellerDB->setData(array("seller_id" => "id"));
            $liveRelSellerDB->foreignKey();
        }

        $liveGoodsObj = new IModel('aliyun_live_goods');
        if (!$liveGoodsObj->exists())
        {
            $data = array(
                "comment" => '直播推荐商品',
                "column"  => array(
                    "id"        => array("type" => "int(11) unsigned", 'auto_increment' => 1),
                    "title"     => array("type" => "varchar(100)", "comment" => "推荐标题"),
                    "seller_id" => array("type" => "int(11) unsigned", "default" => "0", "comment" => "商家ID"),
                    "goods_id"  => array("type" => "int(11) unsigned", "default" => "0", "comment" => "商品ID"),
                    "sort"      => array("type" => "int(11) unsigned", "default" => "0", "comment" => "排序"),
                ),
                "index"   => array("primary" => "id", "key" => "seller_id"),
            );
            $liveGoodsObj->setData($data);
            unset($data);
            $liveGoodsObj->createTable();
            //外键约束
            $liveGoodsRelSellerDB = new IModel('aliyun_live_goods,seller');
            $liveGoodsRelSellerDB->setData(array("seller_id" => "id"));
            $liveGoodsRelSellerDB->foreignKey();
        }

        $liveFollowObj = new IModel('aliyun_live_follow');
        if (!$liveFollowObj->exists())
        {
            $data = array(
                "comment" => '直播关注',
                "column"  => array(
                    "id"          => array("type" => "int(11) unsigned", 'auto_increment' => 1),
                    "user_id"     => array("type" => "int(11)", "comment" => "用户ID"),
                    "seller_id"   => array("type" => "int(11) unsigned", "default" => "0", "comment" => "商家ID"),
                    "create_time" => array("type" => "datetime", "comment" => "关注时间")
                ),
                "index"   => array("primary" => "id", "key" => "seller_id"),
            );
            $liveFollowObj->setData($data);
            unset($data);
            $liveFollowObj->createTable();
            //外键约束
            $liveFollowRelSellerDB = new IModel('aliyun_live_follow,seller');
            $liveFollowRelSellerDB->setData(array("seller_id" => "id"));
            $liveFollowRelSellerDB->foreignKey();
        }

        return true;
    }

    //插件卸载
    public static function uninstall()
    {
        $liveObj = new IModel('aliyun_live');
        $liveObj->dropTable();
        $liveGoodsObj = new IModel('aliyun_live_goods');
        $liveGoodsObj->dropTable();
        $liveFollowObj = new IModel('aliyun_live_follow');
        $liveFollowObj->dropTable();
        return true;
    }

    //注册事件
    public function reg()
    {
        //系统 菜单
        plugin::reg("onSystemMenuCreate", function ()
        {
            $link                            = "/plugins/list_seller";
            $link                            = "javascript:art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'" . $this->name() . "',width:'100%',height:'100%',id:'list_seller'});";
            Menu::$menu["插件"]["插件管理"][$link] = '直播商家审核';

            $link                            = "/plugins/list_live_ing";
            $link                            = "javascript:art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'" . $this->name() . "',width:'100%',height:'100%',id:'list_live_ing'});";
            Menu::$menu["插件"]["插件管理"][$link] = '直播中管理';

            $link                            = "/plugins/list_live_black";
            $link                            = "javascript:art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'" . $this->name() . "',width:'100%',height:'100%',id:'list_live_black'});";
            Menu::$menu["插件"]["插件管理"][$link] = '直播间黑名单';
        });

        //商家 配置菜单
        plugin::reg("onSellerMenuCreate", function ()
        {
            $link                            = "/seller/live_edit";
            $link                            = "javascript:art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'商户直播配置',width:'100%',height:'100%',id:'live_setting'});";
            menuSeller::$menu["配置模块"][$link] = '商户直播配置';

            $link                            = "/seller/live_info";
            $link                            = "javascript:art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'商户直播信息',width:'100%',height:'100%',id:'live_info'});";
            menuSeller::$menu["配置模块"][$link] = '商户直播信息';

            $link                            = "/seller/live_recommend_goods";
            $link                            = "javascript:art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'直播推荐商品',width:'100%',height:'100%',id:'live_recommend_goods'});";
            menuSeller::$menu["配置模块"][$link] = '直播推荐商品';

            $link                            = "/seller/live_follows";
            $link                            = "javascript:art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'直播粉丝列表',width:'100%',height:'100%',id:'live_follows'});";
            menuSeller::$menu["配置模块"][$link] = '直播粉丝列表';
        });

        //个人中心 菜单
        plugin::reg("onUcenterMenuCreate", function ()
        {
            $link                             = "/ucenter/liveing";
            $link                             = "javascript:void(art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'直播中',width:'100%',height:'100%',id:'liveing',fixed:true,lock:true,drag:false}));";
            menuUcenter::$menu["商家直播"][$link] = "直播中";
            menuUcenter::$ico["直播中"]          = "fa fa-life-ring";

            $link                             = "/ucenter/live_follows";
            $link                             = "javascript:void(art.dialog.open('" . IUrl::creatUrl($link) . "',{title:'关注列表',width:'100%',height:'100%',id:'live_follows',fixed:true,lock:true,drag:false}));";
            menuUcenter::$menu["商家直播"][$link] = "关注列表";
            menuUcenter::$ico["关注列表"]         = "fa fa-star";
        });

        //商家 直播配置
        plugin::reg("onBeforeCreateAction@seller@live_edit", function ()
        {
            self::controller()->live_edit = function ()
            {
                $seller_id = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $seller_id = IFilter::act($seller_id, 'int');
                $liveObj   = new IModel('aliyun_live');
                $liveRow   = $liveObj->getObj('seller_id = ' . $seller_id);
                $data      = array();

                if ($liveRow && $liveRow['content'])
                {
                    $data                = JSON::decode($liveRow['content']);
                    $viewArray['create'] = false;
                    $viewArray['status'] = $liveRow['status'];
                } else
                {
                    $viewArray['create'] = true;
                }
                $viewArray['content'] = $data;
                $viewArray['Theme']   = $this->getTheme();
                $this->view('live_edit', $viewArray);
            };
        });

        //商家 直播配置更新
        plugin::reg("onBeforeCreateAction@seller@live_update", function ()
        {
            self::controller()->live_update = function ()
            {
                $seller_id         = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $room_name         = IFilter::act(IReq::get('room_name'));
                $room_desc         = IFilter::act(IReq::get('room_desc'));

                $data = array(
                    'room_name'         => $room_name,
                    'room_desc'         => $room_desc,
                );

                if (isset($_FILES['room_img']['name']) && $_FILES['room_img']['name'])
                {
                    $uploadDir = IWeb::$app->config['upload'] . '/room_img';
                    $uploadObj = new PhotoUpload($uploadDir);
                    $uploadObj->setIterance(false);
                    $photoInfo = $uploadObj->run();
                    if (isset($photoInfo['room_img']['img']) && file_exists($photoInfo['room_img']['img']))
                    {
                        $data['room_img'] = $photoInfo['room_img']['img'];
                    }
                } else
                {
                    $room_img_update = IFilter::act(IReq::get('room_img_update'));
                    if ($room_img_update)
                    {
                        $data['room_img'] = $room_img_update;
                    }
                }

                $dataJson = JSON::encode($data);

                //保存数据库
                $liveObj = new IModel('aliyun_live');
                if ($liveObj->getObj('seller_id != ' . $seller_id . ' and room_name = "' . $room_name . '"'))
                {
                    die("保存失败<script>parent.tips('房间名称['.$room_name.']已经存在');parent.art.dialog.list['live_setting'].close();</script>");
                }

                if ($liveRow = $liveObj->getObj('seller_id = ' . $seller_id))
                {
                    $liveObj->setData(array('content' => $dataJson, 'room_name' => $room_name, 'status' => $liveRow['status']));
                    $liveObj->update('seller_id = ' . $seller_id);
                } else
                {
                    $status = 0;
                    if ($this->Examine == 0)
                    {
                        $status = 1;
                    }
                    $liveObj->setData(array(
                        'content'   => $dataJson,
                        'room_name' => $room_name,
                        'seller_id' => $seller_id,
                        'status'    => $status,
                    ));
                    $liveObj->add();
                }
                die("保存成功<script>parent.tips('保存成功');parent.art.dialog.list['live_setting'].close();</script>");
            };
        });

        //商家 直播信息
        plugin::reg("onBeforeCreateAction@seller@live_info", function ()
        {
            self::controller()->live_info = function ()
            {
                $seller_id = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $seller_id = IFilter::act($seller_id, 'int');
                $liveObj   = new IModel('aliyun_live');
                $liveRow   = $liveObj->getObj('seller_id = ' . $seller_id);
                if ($liveRow && $liveRow['content'])
                {
                    if ($liveRow['status'] != 1)
                    {
                        die("房间处于审核中...<script>parent.tips('房间处于审核中...');parent.art.dialog.list['live_info'].close();</script>");
                    } else
                    {
                        $RTMPPublishURL = $this->getPushUrl('room_' . $seller_id);
                        $this->view('live_info', array(
                            'RTMPPublishURL' => $RTMPPublishURL,
                            'URL'            => substr($RTMPPublishURL, 0, strpos($RTMPPublishURL, $this->AppName)) . $this->AppName . '/',
                            'StreamName'     => str_replace($this->AppName . '/', '', substr($RTMPPublishURL, strpos($RTMPPublishURL, $this->AppName))),
                            'seller_id'      => $seller_id
                        ));
                    }
                } else
                {
                    die("请先配置直播<script>parent.tips('请先配置直播');parent.art.dialog.list['live_info'].close();</script>");
                }
            };
        });

        //商家 关注列表
        plugin::reg("onBeforeCreateAction@seller@live_follows", function ()
        {
            self::controller()->live_follows = function ()
            {
                $seller_id  = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $page       = IReq::get('page') ? IFilter::act(IReq::get('page'), 'int') : 1;
                $Db         = new IQuery('aliyun_live_follow as alf');
                $Db->join   = 'left join seller as s on alf.seller_id=s.id left join user as u on alf.user_id=u.id';
                $Db->fields = 'alf.create_time,u.username,u.head_ico';
                $Db->where  = 'alf.seller_id = ' . $seller_id;
                $Db->order  = 'alf.create_time desc ';
                $Db->page   = $page;
                $follows    = $Db->find();
                $this->view('live_follows', array('follows' => $follows));
            };
        });

        //商家 推流历史
        plugin::reg("onBeforeCreateAction@seller@stream_publish_list", function ()
        {
            self::controller()->stream_publish_list = function ()
            {
                $seller_id = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                if ($seller_id)
                {
                    $data['LiveStreamPublishInfo'] = array();
                    $resp                          = $this->DescribeLiveStreamsPublishList('room_' . $seller_id, $this->pageSize, $this->pageObj->index);
                    $this->pageObj->totalpage      = $resp['TotalPage'];
                    $this->pageObj->rows           = $resp['TotalNum'];
                    $this->pageObj->lastpage       = floor(($this->pageObj->rows-1)/$this->pageObj->pagesize)+1;
                    if ($resp['TotalNum'] > 0)
                    {
                        $data['TotalPage'] = $resp['TotalPage'];
                        $data['TotalNum']  = $resp['TotalNum'];
                        $data['PageNum']   = $resp['PageNum'];
                        foreach ($resp['PublishInfo']['LiveStreamPublishInfo'] as $key => $value)
                        {
                            $value['PublishTime']                = date('Y-m-s H:i:s', strtotime($value['PublishTime']));
                            $value['StopTime']                   = date('Y-m-s H:i:s', strtotime($value['StopTime']));
                            $data['LiveStreamPublishInfo'][$key] = $value;
                        }
                    }
                    $this->view('list_live_publish', array('data' => $data, 'pageObj' => $this->pageObj));
                }
            };
        });

        //商家 推荐商品列表
        plugin::reg("onBeforeCreateAction@seller@live_recommend_goods", function ()
        {
            self::controller()->live_recommend_goods = function ()
            {
                $seller_id  = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $Db         = new IQuery('aliyun_live_goods as ald');
                $Db->join   = 'left join goods as g on ald.goods_id=g.id';
                $Db->fields = 'ald.title,g.name,g.img,g.id as goods_id,ald.id,ald.sort';
                $Db->where  = 'ald.seller_id = ' . $seller_id;
                $Db->order  = 'ald.sort desc ';
                $data       = $Db->find();
                $this->view('live_recommend_goods', array('data' => $data, 'seller_id' => $seller_id));
            };
        });

        //商家 推荐商品编辑
        plugin::reg("onBeforeCreateAction@seller@live_recommend_goods_edit", function ()
        {
            self::controller()->live_recommend_goods_edit = function ()
            {
                $seller_id = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $id        = IFilter::act(IReq::get('id'), 'int');
                $data      = array();
                $result    = array();
                if ($id)
                {
                    $DB   = new IModel('aliyun_live_goods');
                    $data = $DB->getObj('id = ' . $id . ' and seller_id = ' . $seller_id);

                    $goodsObj = new IModel('goods');
                    $goodsRow = $goodsObj->getObj('id = ' . $data['goods_id']);

                    $result = array(
                        'data' => $goodsRow,
                    );
                }
                $this->view('live_recommend_goods_edit', array('data' => $data, 'seller_id' => $seller_id, 'goodsRow' => JSON::encode($result)));
            };
        });

        //商家 推荐商品更新
        plugin::reg("onBeforeCreateAction@seller@live_recommend_goods_update", function ()
        {
            self::controller()->live_recommend_goods_update = function ()
            {
                $seller_id = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $id        = IFilter::act(IReq::get('id'), 'int');
                $DB        = new IModel('aliyun_live_goods');
                $dataArray = array(
                    'title'     => IFilter::act(IReq::get('title', 'post')),
                    'goods_id'  => IFilter::act(IReq::get('goods_id'), 'int'),
                    'sort'      => IFilter::act(IReq::get('sort'), 'int'),
                    'seller_id' => $seller_id,
                );
                $DB->setData($dataArray);
                if ($id)
                {
                    $where = 'id = ' . $id . ' and seller_id = ' . $seller_id;
                    if ($DB->getObj($where))
                    {
                        $DB->update($where);
                    }
                } else
                {
                    $id = $DB->add();
                }
                die("<script>window.location.href='" . IUrl::creatUrl('/seller/live_recommend_goods') . "';</script>");
            };
        });

        //商家 推荐商品删除
        plugin::reg("onBeforeCreateAction@seller@live_recommend_goods_del", function ()
        {
            self::controller()->live_recommend_goods_del = function ()
            {
                $seller_id = self::controller()->seller ? self::controller()->seller['seller_id'] : 0;
                $id        = IFilter::act(IReq::get('id'), 'int');
                if ($id)
                {
                    $DB = new IModel('aliyun_live_goods');
                    if ($DB->del('id = ' . $id . ' and seller_id = ' . $seller_id))
                    {
                        die(JSON::encode(array('result' => 'success')));
                    } else
                    {
                        die(JSON::encode(array('result' => 'fail')));
                    }
                }
            };
        });

        //系统 商家审核列表
        plugin::reg("onBeforeCreateAction@plugins@list_seller", function ()
        {
            self::controller()->list_seller = function ()
            {
                $this->view('list_seller');
            };
        });

        //系统 商家审核操作
        plugin::reg("onBeforeCreateAction@plugins@list_seller_edit", function ()
        {
            self::controller()->list_seller_edit = function ()
            {
                $id     = IFilter::act(IReq::get('id'), 'int');
                $status = IFilter::act(IReq::get('status'), 'int');
                //保存数据库
                $liveObj = new IModel('aliyun_live');
                if ($liveRow = $liveObj->getObj('id = ' . $id))
                {
                    $liveObj->setData(array('status' => $status));
                    $liveObj->update('id = ' . $id);

                    $db     = new IModel('seller');
                    $row    = $db->getObj($liveRow['seller_id']);
                    $mobile = $row && $row['mobile'] ? $row['mobile'] : "";
                    Hsms::send($mobile, "您的商家账号直播状态更新[" . ($status == 1) ? '通过' : '禁用' . "]", 0);
                    $this->view('list_seller');
                }
            };
        });

        //系统 直播间管理列表
        plugin::reg("onBeforeCreateAction@plugins@list_live_ing", function ()
        {
            self::controller()->list_live_ing = function ()
            {
                $data['LiveStreamOnlineInfo'] = array();
                $resp                         = $this->DescribeLiveStreamsOnlineList('', $this->pageSize, $this->pageObj->index);
                if ($resp['TotalNum'] > 0)
                {
                    $SellerDb                 = new IQuery('seller as s');
                    $data['TotalPage']        = $resp['TotalPage'];
                    $data['TotalNum']         = $resp['TotalNum'];
                    $data['PageNum']          = $resp['PageNum'];
                    $this->pageObj->totalpage = $resp['TotalPage'];
                    $this->pageObj->rows      = $resp['TotalNum'];
                    $this->pageObj->lastpage  = floor(($this->pageObj->rows-1)/$this->pageObj->pagesize)+1;
                    foreach ($resp['OnlineInfo']['LiveStreamOnlineInfo'] as $key => $value)
                    {
                        $value['PublishTime'] = date('Y-m-s H:i:s', strtotime($value['PublishTime']));
                        $seller_id            = str_replace('room_', '', $value['StreamName']);
                        $SellerDb->join       = 'left join aliyun_live as al on s.id=al.seller_id';
                        $SellerDb->fields     = 's.seller_name,s.true_name,al.room_name,al.seller_id';
                        $SellerDb->where      = 's.id = ' . $seller_id;
                        $row                  = $SellerDb->find();
                        if ($row)
                        {
                            $row                                = $row[0];
                            $value['seller_id']                 = $row['seller_id'];
                            $value['room_name']                 = $row['room_name'];
                            $value['seller_name']               = $row['seller_name'];
                            $value['true_name']                 = $row['true_name'];
                            $data['LiveStreamOnlineInfo'][$key] = $value;
                        }
                    }
                }

                $this->view('list_live_ing', array(
                    'data'    => $data,
                    'pageObj' => $this->pageObj,
                ));
            };
        });

        //系统 直播间黑名单
        plugin::reg("onBeforeCreateAction@plugins@list_live_black", function ()
        {
            self::controller()->list_live_black = function ()
            {
                $forbidData['StreamUrls'] = array();
                $resp                     = $this->DescribeLiveStreamsBlockList($this->pageSize, $this->pageObj->index);
                if ($resp['TotalNum'] > 0)
                {
                    $SellerDb                 = new IQuery('seller as s');
                    $forbidData['TotalPage']  = $resp['TotalPage'];
                    $forbidData['TotalNum']   = $resp['TotalNum'];
                    $forbidData['PageNum']    = $resp['PageNum'];
                    $this->pageObj->totalpage = $resp['TotalPage'];
                    $this->pageObj->rows      = $resp['TotalNum'];
                    $this->pageObj->lastpage  = floor(($this->pageObj->rows-1)/$this->pageObj->pagesize)+1;
                    foreach ($resp['StreamUrls']['StreamUrl'] as $key => $value)
                    {
                        $seller_id        = str_replace($this->PushUrl . '/' . $this->AppName . '/room_', '', $value);
                        $SellerDb->join   = 'left join aliyun_live as al on s.id=al.seller_id';
                        $SellerDb->fields = 's.seller_name,s.true_name,al.room_name,al.seller_id';
                        $SellerDb->where  = 's.id = ' . $seller_id;
                        $row              = $SellerDb->find();
                        if ($row)
                        {
                            $row                            = $row[0];
                            $forbidValue['seller_id']       = $row['seller_id'];
                            $forbidValue['room_name']       = $row['room_name'];
                            $forbidValue['seller_name']     = $row['seller_name'];
                            $forbidValue['true_name']       = $row['true_name'];
                            $forbidValue['StreamUrl']       = $value;
                            $forbidData['StreamUrls'][$key] = $forbidValue;
                        }
                    }
                }

                $this->view('list_live_black', array(
                    'forbidData' => $forbidData,
                    'pageObj'    => $this->pageObj
                ));
            };
        });

        //系统 禁用房间
        plugin::reg("onBeforeCreateAction@plugins@forbid_live_stream", function ()
        {
            self::controller()->forbid_live_stream = function ()
            {
                $seller_id = IFilter::act(IReq::get('seller_id'), 'int');
                if ($seller_id)
                {
                    $resp = $this->ForbidLiveStream('room_' . $seller_id);
                    if (isset($resp['RequestId']))
                    {
                        die(JSON::encode(array('result' => 'success')));
                    } else
                    {
                        die(JSON::encode(array('result' => 'fail')));
                    }
                }
            };
        });

        //系统 启用房间
        plugin::reg("onBeforeCreateAction@plugins@resume_live_stream", function ()
        {
            self::controller()->resume_live_stream = function ()
            {
                $seller_id = IFilter::act(IReq::get('seller_id'), 'int');
                if ($seller_id)
                {
                    $resp = $this->ResumeLiveStream('room_' . $seller_id);
                    if (isset($resp['RequestId']))
                    {
                        die(JSON::encode(array('result' => 'success')));
                    } else
                    {
                        die(JSON::encode(array('result' => 'fail')));
                    }
                }
            };
        });

        //系统 推流历史
        plugin::reg("onBeforeCreateAction@plugins@stream_publish_list", function ()
        {
            self::controller()->stream_publish_list = function ()
            {
                $seller_id = IFilter::act(IReq::get('seller_id'), 'int');
                if ($seller_id)
                {
                    $data['LiveStreamPublishInfo'] = array();
                    $resp                          = $this->DescribeLiveStreamsPublishList('room_' . $seller_id, $this->pageSize, $this->pageObj->index);
                    if ($resp['TotalNum'] > 0)
                    {
                        $data['TotalPage']        = $resp['TotalPage'];
                        $data['TotalNum']         = $resp['TotalNum'];
                        $data['PageNum']          = $resp['PageNum'];
                        $this->pageObj->totalpage = $resp['TotalPage'];
                        $this->pageObj->rows      = $resp['TotalNum'];
                        $this->pageObj->lastpage  = floor(($this->pageObj->rows-1)/$this->pageObj->pagesize)+1;
                        foreach ($resp['PublishInfo']['LiveStreamPublishInfo'] as $key => $value)
                        {
                            $value['PublishTime']                = date('Y-m-s H:i:s', strtotime($value['PublishTime']));
                            $value['StopTime']                   = date('Y-m-s H:i:s', strtotime($value['StopTime']));
                            $data['LiveStreamPublishInfo'][$key] = $value;
                        }
                    }
                    $this->view('list_live_publish', array('data' => $data, 'pageObj' => $this->pageObj));
                }
            };
        });

        //系统 关注列表
        plugin::reg("onBeforeCreateAction@plugins@live_follows", function ()
        {
            self::controller()->live_follows = function ()
            {
                $seller_id = IFilter::act(IReq::get('seller_id'), 'int');
                if ($seller_id)
                {
                    $page       = IReq::get('page') ? IFilter::act(IReq::get('page'), 'int') : 1;
                    $Db         = new IQuery('aliyun_live_follow as alf');
                    $Db->join   = 'left join seller as s on alf.seller_id=s.id left join user as u on alf.user_id=u.id';
                    $Db->fields = 'alf.create_time,u.username,u.head_ico';
                    $Db->where  = 'alf.seller_id = ' . $seller_id;
                    $Db->order  = 'alf.create_time desc ';
                    $Db->page   = $page;
                    $follows    = $Db->find();
                    $this->view('live_follows', array('follows' => $follows));
                }
            };
        });

        //前台 打开直播间
        plugin::reg("onBeforeCreateAction@site@live_show", function ()
        {
            self::controller()->live_show = function ()
            {
                $seller_id  = IFilter::act(IReq::get('seller_id'), 'int');
                $device     = IFilter::act(IReq::get('device'));
                $sellerInfo = api::run('getSellerInfo', $seller_id);
                if (!$sellerInfo)
                {
                    die();
                }

                $resp = $this->DescribeLiveStreamsOnlineList('room_' . $seller_id);
                if ($resp['TotalNum'] == 0)
                {
                    // Util::showMessage('直播未在进行中！');
                }

                $liveObj = new IModel('aliyun_live');
                $liveRow = $liveObj->getObj('seller_id = ' . $seller_id);
                if ($liveRow && $liveRow['content'] && $liveRow['status'] == 1)
                {
                    $liveRow = JSON::decode($liveRow['content']);
                    $playUrl = $this->getPlayUrl('room_' . $seller_id);
                    if (IClient::getDevice() == 'mobile')
                    {
                        $playUrl = $playUrl['hls'];
                    } else
                    {
                        $playUrl = $playUrl['rtmp'];
                    }

                    $Db         = new IQuery('aliyun_live_goods as ald');
                    $Db->join   = 'left join goods as g on ald.goods_id=g.id';
                    $Db->fields = 'ald.title,g.name,g.img,g.id as goods_id,ald.id,ald.sort,g.sell_price,g.market_price';
                    $Db->where  = 'ald.seller_id = ' . $seller_id;
                    $Db->order  = 'ald.sort desc ';
                    $goods      = $Db->find();

                    $RongToken       = '';
                    $visitor_default = '/plugins/aliyun_live/public/images/visitor_default.jpg';

                    if (IWeb::$app->getController()->user['user_id'])
                    {
                        $user     = IWeb::$app->getController()->user;
                        $userInfo = [
                            'id'       => $user['user_id'],
                            'name'     => $user['username'],
                            'portrait' => $user['head_ico'] != "" ? $user['head_ico'] : $visitor_default,
                            'visitor'  => 0
                        ];
                    } else
                    {
                        if (ISafe::get('visitor_id'))
                        {
                            $uniqidId = ISafe::get('visitor_id');
                        } else
                        {
                            $uniqidId = uniqid();
                            ISafe::set('visitor_id', $uniqidId);
                        }
                        $userInfo = [
                            'id'       => $uniqidId,
                            'name'     => '游客' . $uniqidId,
                            'portrait' => $visitor_default,
                            'visitor'  => 1
                        ];
                    }

                    $register = $this->getRong()->getUser()->register($userInfo);
                    if ($register['code'] == 200)
                    {
                        $RongToken = $register['token'];
                    }

                    $isFollow = 0;
                    if (IWeb::$app->getController()->user['user_id'])
                    {
                        $liveFollowObj = new IModel('aliyun_live_follow');
                        if ($liveFollowObj->getObj('seller_id = ' . $seller_id . ' and user_id = ' . IWeb::$app->getController()->user['user_id']))
                        {
                            $isFollow = 1;
                        }
                    }

                    if($device != '')
                    {
                        $_device = $device;
                    }
                    else
                    {
                        $_device = IClient::getDevice();
                    }
                    $live_show = 'Theme/' . $_device . '/live_show';
                    $this->view($live_show, array(
                        'playUrl'    => $playUrl,
                        'seller_id'  => $seller_id,
                        'onlineRow'  => $liveRow,
                        'goods'      => $goods,
                        'UserInfo'   => $userInfo,
                        'RongToken'  => $RongToken,
                        'RongAppKey' => $this->RongAppKey,
                        'sellerInfo' => $sellerInfo,
                        'Device'     => IClient::getDevice(),
                        'isFollow'   => $isFollow
                    ));
                }
            };
        });

        //前台 获取头像
        plugin::reg("onBeforeCreateAction@site@live_headico", function ()
        {
            self::controller()->live_headico = function ()
            {
                $ids  = IFilter::act(IReq::get('ids'));
                if ($ids == '')
                {
                    die();
                }
                $ids       = substr($ids,0,-1);
                $ids       = explode(',',$ids);
                foreach ($ids as $key=>$value)
                {
                    if(!is_numeric($value))
                    {
                        unset($ids[$key]);
                    }
                }
                if(count($ids) == 0)
                {
                    die();
                }
                $ids       = implode($ids,',');
                $userObj   = new IModel('user');
                $data      = $userObj->query('id in (' . $ids . ')','head_ico,id');
                foreach ($data as $key=>$value)
                {
                    if($value['head_ico'] == '')
                    {
                        unset($data[$key]);
                    }
                }
                if(count($data) > 0)
                {
                    die(JSON::encode(array('result' => 'success','data'=>$data)));
                }
            };
        });

        //个人中心-直播中
        plugin::reg("onBeforeCreateAction@ucenter@liveing", function ()
        {
            self::controller()->liveing = function ()
            {
                $data['LiveStreamOnlineInfo'] = array();
                $resp                         = $this->DescribeLiveStreamsOnlineList('', $this->pageSize, $this->pageObj->index);
                if ($resp['TotalNum'] > 0)
                {
                    $SellerDb                 = new IQuery('seller as s');
                    $data['TotalPage']        = $resp['TotalPage'];
                    $data['TotalNum']         = $resp['TotalNum'];
                    $data['PageNum']          = $resp['PageNum'];
                    $this->pageObj->totalpage = $resp['TotalPage'];
                    $this->pageObj->rows      = $resp['TotalNum'];
                    $this->pageObj->lastpage  = floor(($this->pageObj->rows-1)/$this->pageObj->pagesize)+1;
                    foreach ($resp['OnlineInfo']['LiveStreamOnlineInfo'] as $key => $value)
                    {
                        $value['PublishTime'] = date('Y-m-s H:i:s', strtotime($value['PublishTime']));
                        $seller_id            = str_replace('room_', '', $value['StreamName']);
                        $SellerDb->join       = 'left join aliyun_live as al on s.id=al.seller_id';
                        $SellerDb->fields     = 's.seller_name,s.true_name,al.room_name,al.seller_id';
                        $SellerDb->where      = 's.id = ' . $seller_id;
                        $row                  = $SellerDb->find();
                        if ($row)
                        {
                            $row                                = $row[0];
                            $value['seller_id']                 = $row['seller_id'];
                            $value['room_name']                 = $row['room_name'];
                            $value['seller_name']               = $row['seller_name'];
                            $value['true_name']                 = $row['true_name'];
                            $data['LiveStreamOnlineInfo'][$key] = $value;
                        }
                    }
                }
                $this->view('ucenter_live_ing', array('data' => $data, 'pageObj' => $this->pageObj));
            };
        });

        //个人中心 关注列表
        plugin::reg("onBeforeCreateAction@ucenter@live_follows", function ()
        {
            self::controller()->live_follows = function ()
            {
                $page       = IReq::get('page') ? IFilter::act(IReq::get('page'), 'int') : 1;
                $Db         = new IQuery('aliyun_live_follow as alf');
                $Db->join   = 'left join seller as s on alf.seller_id=s.id left join user as u on alf.user_id=u.id';
                $Db->fields = 'alf.create_time,s.seller_name,s.logo,s.id';
                $Db->where  = 'alf.user_id = ' . IWeb::$app->getController()->user['user_id'];
                $Db->order  = 'alf.create_time desc ';
                $Db->page   = $page;
                $follows    = $Db->find();
                foreach ($follows as $key => $value)
                {
                    $resp = $this->DescribeLiveStreamsOnlineList('room_' . $value['id']);
                    if ($resp['TotalNum'] == 0)
                    {
                        $follows[$key]['liveing'] = 0;
                    } else
                    {
                        $follows[$key]['liveing'] = 1;
                    }
                }
                $this->view('ucenter_follows', array('follows' => $follows));
            };
        });

        //用户关注
        plugin::reg("onBeforeCreateAction@ucenter@live_follow", function ()
        {
            self::controller()->live_follow = function ()
            {
                $seller_id = IFilter::act(IReq::get('seller_id'), 'int');
                $liveObj   = new IModel('aliyun_live');
                $liveRow   = $liveObj->getObj('seller_id = ' . $seller_id . ' and status = 1');
                if (!$liveRow)
                {
                    die();
                }
                //必须为登录用户
                if (!IWeb::$app->getController()->user['user_id'])
                {
                    $url = IUrl::creatUrl('simple/login') . '&callback=/site/live_show/seller_id/' . $seller_id;
                    die("<script>window.location='" . $url . "'</script>");
                }

                $liveFollowObj = new IModel('aliyun_live_follow');
                if ($liveFollowObj->getObj('seller_id = ' . $seller_id . ' and user_id = ' . IWeb::$app->getController()->user['user_id']))
                {
                    die();
                }
                $data['seller_id']   = $seller_id;
                $data['user_id']     = IWeb::$app->getController()->user['user_id'];
                $data['create_time'] = date('Y-m-d H:i:s');
                $liveFollowObj->setData($data);
                if ($liveFollowObj->add())
                {
                    die(JSON::encode(array('result' => 'success')));
                } else
                {
                    die(JSON::encode(array('result' => 'fail')));
                }
            };
        });

        //用户取消关注
        plugin::reg("onBeforeCreateAction@ucenter@live_follow_cancel", function ()
        {
            self::controller()->live_follow_cancel = function ()
            {
                $seller_id     = IFilter::act(IReq::get('seller_id'), 'int');
                $ajax          = IFilter::act(IReq::get('ajax'), 'int');
                $liveFollowObj = new IModel('aliyun_live_follow');
                if (!$liveFollowRow = $liveFollowObj->getObj('seller_id = ' . $seller_id . ' and user_id = ' . IWeb::$app->getController()->user['user_id']))
                {
                    die();
                }
                if ($liveFollowObj->del('id = ' . $liveFollowRow['id']))
                {
                    if ($ajax == 1)
                    {
                        die(JSON::encode(array('result' => 'success')));
                    } else
                    {
                        die("<script>window.location.href='" . IUrl::creatUrl('/ucenter/live_follow') . "';</script>");
                    }
                } else
                {
                    if ($ajax == 1)
                    {
                        die(JSON::encode(array('result' => 'fail')));
                    } else
                    {
                        die("<script>window.location.href='" . IUrl::creatUrl('/ucenter/live_follow') . "';</script>");
                    }
                }
            };
        });
    }

    // 查看指定域名下（或者指定域名下某个应用）的所有正在推的流的信息。
    private function DescribeLiveStreamsOnlineList($StreamName = '', $PageSize = 3000, $PageNumber = 1)
    {
        $request = new live\Request\V20161101\DescribeLiveStreamsOnlineListRequest();
        $request->setActionName('DescribeLiveStreamsOnlineList');
        $request->setDomainName($this->PushUrl);
        $request->setAppName($this->AppName);
        if ($StreamName != '')
        {
            $request->setStreamName($StreamName);
        }
        $request->setPageSize($PageSize);
        $request->setPageNum($PageNumber);
        try
        {
            $response = $this->getClient()->getAcsResponse($request);
            return $this->object_to_array($response);
        } catch (\Exception $e)
        {
            var_dump($e->getMessage());
            exit();
        }
    }

    // 获取域名下直播流播放的黑名单。
    private function DescribeLiveStreamsBlockList($PageSize = 3000, $PageNumber = 1)
    {
        $request = new live\Request\V20161101\DescribeLiveStreamsBlockListRequest();
        $request->setActionName('DescribeLiveStreamsBlockList');
        $request->setDomainName($this->PushUrl);
        $request->setPageSize($PageSize);
        $request->setPageNum($PageNumber);
        try
        {
            $response = $this->getClient()->getAcsResponse($request);
            return $this->object_to_array($response);
        } catch (\Exception $e)
        {
            var_dump($e->getMessage());
            exit();
        }
    }

    // 禁止某条流的推送，可以预设某个时刻将流恢复。
    private function ForbidLiveStream($StreamName)
    {
        $request = new live\Request\V20161101\ForbidLiveStreamRequest();
        $request->setActionName('ForbidLiveStream');
        $request->setDomainName($this->PushUrl);
        $request->setAppName($this->AppName);
        $request->setLiveStreamType('publisher');
        $request->setStreamName($StreamName);
        try
        {
            $response = $this->getClient()->getAcsResponse($request);
            return $this->object_to_array($response);
        } catch (\Exception $e)
        {
            var_dump($e->getMessage());
            exit();
        }
    }

    // 恢复某条流的推送。
    private function ResumeLiveStream($StreamName)
    {
        $request = new live\Request\V20161101\ResumeLiveStreamRequest();
        $request->setActionName('ResumeLiveStream');
        $request->setDomainName($this->PushUrl);
        $request->setAppName($this->AppName);
        $request->setLiveStreamType('publisher');
        $request->setStreamName($StreamName);
        try
        {
            $response = $this->getClient()->getAcsResponse($request);
            return $this->object_to_array($response);
        } catch (\Exception $e)
        {
            var_dump($e->getMessage());
            exit();
        }
    }

    // 获取推流历史
    private function DescribeLiveStreamsPublishList($StreamName, $PageSize = 3000, $PageNumber = 1)
    {
        $request = new live\Request\V20161101\DescribeLiveStreamsPublishListRequest();
        $request->setDomainName($this->PushUrl);
        $request->setAppName($this->AppName);
        $request->setStreamName($StreamName);
        $request->setStartTime(date('Y-m-d\TH:i:s\Z', strtotime("-30 days") - 3600 * 8));
        $request->setEndTime(date('Y-m-d\TH:i:s\Z', strtotime("-8 hours")));
        $request->setPageSize($PageSize);
        $request->setPageNumber($PageNumber);
        try
        {
            $response = $this->getClient()->getAcsResponse($request);
            return $this->object_to_array($response);
        } catch (\Exception $e)
        {
            var_dump($e->getMessage());
            exit();
        }
    }

    //获取推流地址 优先将视频推流至距离用户最近的CDN节点，后通过阿里内网将视频流推至直播中心
    private function getPushUrl($streamName)
    {
        $time    = time() + 1800;
        $rand    = 0;
        $strpush = "/$this->AppName/$streamName-$time-$rand-0-$this->PushUrlKey";
        $url     = 'rtmp://' . $this->PushUrl . '/' . $this->AppName . '/' . $streamName . '?auth_key=' . $time . '-' . $rand . '-0-' . md5($strpush);
        return $url;
    }

    //获取拉流地址
    private function getPlayUrl($streamName)
    {
        $time        = time() + 1800;
        $rand        = 0;
        $strviewrtmp = '/' . $this->AppName . '/' . $streamName . '-' . $time . '-' . $rand . '-0-' . $this->PlayUrlKey;
        $strviewflv  = '/' . $this->AppName . '/' . $streamName . '.flv-' . $time . '-' . $rand . '-0-' . $this->PlayUrlKey;
        $strviewm3u8 = '/' . $this->AppName . '/' . $streamName . '.m3u8-' . $time . '-' . $rand . '-0-' . $this->PlayUrlKey;
        $rtmpurl     = 'rtmp://' . $this->PlayUrl . '/' . $this->AppName . '/' . $streamName . '?auth_key=' . $time . '-' . $rand . '-0-' . md5($strviewrtmp);
        $flvurl      = 'http://' . $this->PlayUrl . '/' . $this->AppName . '/' . $streamName . '.flv?auth_key=' . $time . '-' . $rand . '-0-' . md5($strviewflv);
        $m3u8url     = 'http://' . $this->PlayUrl . '/' . $this->AppName . '/' . $streamName . '.m3u8?auth_key=' . $time . '-' . $rand . '-0-' . md5($strviewm3u8);
        return array('rtmp' => $rtmpurl, 'flv' => $flvurl, 'hls' => $m3u8url);
    }

    //获取阿里云直播实例化
    private function getClient()
    {
        if ($this->client)
        {
            return $this->client;
        }
        $iClientProfile = DefaultProfile::getProfile("cn-hangzhou", $this->AccessKey, $this->SecretKey);
        $this->client   = new DefaultAcsClient($iClientProfile);
        return $this->client;
    }

    //获取融云IM实例化
    private function getRong()
    {
        if ($this->rong)
        {
            return $this->rong;
        }
        $this->rong = new RongCloud\RongCloud($this->RongAppKey, $this->RongAppSecret);
        return $this->rong;
    }

    //获取模板方案名称
    public function getTheme()
    {
        $result   = array();
        $planPath = $this->path() . 'Theme';
        if (is_dir($planPath))
        {
            $dirRes = opendir($planPath);
            while (false !== ($dir = readdir($dirRes)))
            {
                if ($dir[0] == ".")
                {
                    continue;
                }
                $result[] = $dir;
            }
        }
        return $result;
    }

    //对象转数组
    private function object_to_array($obj)
    {
        $obj = (array)$obj;
        foreach ($obj as $k => $v)
        {
            if (gettype($v) == 'resource')
            {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array')
            {
                $obj[$k] = (array)$this->object_to_array($v);
            }
        }
        return $obj;
    }
}